#![allow(unused)]
//*************************************************************/
//      钩子设计模式
//*************************************************************/

pub trait Hook{
    fn before(&self);
    fn after(&self);
}
// 默认实现
impl Hook for () {
    fn before(&self) {println!("调用默认before");}
    fn after(&self) {println!("调用默认after");}
}

struct Framework {
    hook: Vec<Box<dyn Hook>>,
}

impl  Framework {
    fn new() -> Self {
        
        Self { hook:Vec::new() }
    }
    fn run(&self, f: impl FnOnce()) {
        for v in &self.hook {
            v.before();
        }
        f();
        for v in &self.hook {
            v.after();
        }
    }
    fn setHook(&mut self, hook: Box<dyn Hook>) {
        self.hook.push(hook);
    }
}

struct CustomHook;
impl Hook for CustomHook {
    fn before(&self) {
        println!("before 1");
    }
    /// 实现调用默认的after方法
    fn after(&self) { // 编译器要求实现接口要显示实现接口方法
        ().after(); // 显示的调用()单元类型实例提供的after方法,
    }
}
struct CustomHook2;
impl Hook for CustomHook2 {
    fn before(&self) {
        println!("before 2");
    }
    fn after(&self) {
        println!("after 2");
    }
}
fn main() {
    let customhook = Box::new(CustomHook{});
    let customhook2 = Box::new(CustomHook2{});
    let mut f  = Framework::new();
    f.setHook(customhook);
    f.setHook(customhook2);
    f.run(|| println!("hello"));
}